package com.Filters.Zipfilters;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.zip.GZIPOutputStream;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

public class GZIPResponseWrapper extends HttpServletResponseWrapper {
    private GZIPOutputStream gzipStream;
    private PrintWriter printWriter;

    public GZIPResponseWrapper(HttpServletResponse response) throws IOException {
        super(response);
        response.addHeader("Content-Encoding", "gzip");
    }

    public void close() throws IOException {
        this.printWriter.close();
        this.gzipStream.close();
    }

    @Override
    public void flushBuffer() throws IOException {
        this.printWriter.flush();
        super.flushBuffer();
    }

    @Override
    public ServletOutputStream getOutputStream() throws IOException {
        return getResponse().getOutputStream();
    }

    @Override
    public PrintWriter getWriter() throws IOException {
        if (this.printWriter == null) {
            this.gzipStream = new GZIPOutputStream(getResponse().getOutputStream());
            this.printWriter = new PrintWriter(new OutputStreamWriter(this.gzipStream, getResponse().getCharacterEncoding()));
        }
        return this.printWriter;
    }

    @Override
    public void setContentLength(int len) {
        getResponse().setContentLength(len);
    }
}
